package org.balthie.demo.jdk.util.concurrent.collections.queue;

import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;

//它的最大特点时不存储实际元素，而是在内部通过栈或队列结构 QNode保存阻塞线程。
// 生产者(put)与消费者(take) 一一匹配

//https://segmentfault.com/a/1190000016359551
public class SynchronousQueueDemo {
	 static class SynchronousQueueProducer implements Runnable {

	        protected BlockingQueue<String> blockingQueue;
	        final Random random = new Random();

	        public SynchronousQueueProducer(BlockingQueue<String> queue) {
	            this.blockingQueue = queue;
	        }

	        @Override
	        public void run() {
	            while (true) {
	                try {
	                    String data = UUID.randomUUID().toString();
	                    System.out.println( String.format("[%s] put data at [%2$tH:%2$tM:%2$tS %2$tL]", Thread.currentThread().getName(), new Date()));
	                    blockingQueue.put(data);
//	                    blockingQueue.add(e);
//	                    blockingQueue.offer(e);
	                    Thread.sleep(1000);
	                } catch (InterruptedException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	    }

	    static class SynchronousQueueConsumer implements Runnable {

	        protected BlockingQueue<String> blockingQueue;

	        public SynchronousQueueConsumer(BlockingQueue<String> queue) {
	            this.blockingQueue = queue;
	        }

	        @Override
	        public void run() {
	            while (true) {
	                try {
	                    String data = blockingQueue.take();
	                    System.out.println(String.format("[%s] take data at [%2$tH:%2$tM:%2$tS %2$tL]", Thread.currentThread().getName(), new Date()));
	                    Thread.sleep(2000);
	                } catch (InterruptedException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	    }

}
